<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax封装函数</title>
</head>
<body>
    <script type="text/javascript">
        function ajax(tru) {
        	OPS = {
		        type: 'get',
		        url: '',
		        header: {
			        'Content-Type': 'application/json',
		        },
		        data: {},
		        success: function (obj,text) {
		        console.log(obj,text);
	            },
                error: function (obj,text) {
                    console.log(obj,text)
                }
	        }
	        //属性覆盖
            Object.assign(OPS,tru)
            var xhr = new XMLHttpRequest();
            var param = '';
            var url = OPS.url

            if(OPS.type === 'get')
            {
            	for (ops in OPS.data){
            		param += ops + '=' + OPS.data[ops] + '&'
                }
            	param = param.substring(0,param.length-2)
                url = url + '?' + param
            }
            else {
            	if(OPS.header['Content-Type'] === 'application/x-www-form-urlencoded'){
		            for (ops in OPS.data){
			            param += ops + '=' + OPS.data[ops] + '&'
		            }
		            param = param.substring(0,param.length-2)
                }
            	else {

                }
            }
            xhr.open(OPS.type,url);
            if (OPS.type === 'get')
            {
	            xhr.send();
            }
            else{
	            if(OPS.header['Content-Type'] === 'application/x-www-form-urlencoded'){
		            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
		            xhr.send(param)
	            }
	            else {
		            xhr.setRequestHeader('Content-Type','application/json')
	            	xhr.send(JSON.stringify(OPS.data))
	            }
            }
            xhr.onload = function () {

            	var title = xhr.getResponseHeader('Content-Type')
                if(title.includes('application/json'))
                {
                	xhr.responseText = JSON.parse(title)
                }
            	if (xhr.status == 200)
                {
	                OPS.success(xhr,xhr.responseText)
                }
            	else {
            		OPS.error(xhr,xhr.responseText)
                }
            }
        }

        ajax({
            type:'get',
            url:'http://localhost:3000/first',
            header:{
            	'Content-Type':'application/json',
            },
            data: {
            	name:'zhangsan',
                age:20
            },
            success: function (obj,text) {
            	console.log(obj,text);
            },
            error: function (obj,text) {
            	console.log(obj,text)

            }
        })

    </script>
</body>
</html>